<?php

namespace addons\booking\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use addons\booking\model\Order;
use addons\booking\model\OrderCalendar;
use think\Db;

class BookingOrder extends Command
{

    protected function configure()
    {
        $this->setName('booking:order')->setDescription("booking 订单失效");
    }

    /*
     * 订单失效---
     */
    protected function execute(Input $input, Output $output)
    {
        $config = get_addon_config('booking');
        $time = time() - $config['order_timeout'];
        try {
            $order = Order::field('o.*,h.interval_time,h.id house_id')
                ->where(function ($query) use ($time) {
                    $query->where('o.status', 'created')->where('o.createtime', '<=', $time);
                })->whereOr(function ($query) {
                    $query->where('o.checkin_time', strtotime(date('Y-m-d')))->where('o.status', 'toshopay');
                })
                ->where('o.type', 0)
                ->alias('o')
                ->join('booking_house h', 'h.id=o.source_id', 'LEFT')
                ->select();

            //超过设置订单状态为过期     
            if ($order) {
                foreach ($order as $item) {
                    // 启动事务
                    Db::startTrans();
                    try {
                        //房间不存在或在线失效                 
                        if (empty($item['house_id']) || $item['status'] != 'toshopay') {
                            $item->save(['status' => 'expired']);
                            //已预订房间状态修改
                            OrderCalendar::editCalendar($item->orderid);
                        } else {
                            if ($item['interval_time'] <= date('H:i:s')) {
                                $item->save(['status' => 'expired']);
                                //已预订房间状态修改
                                OrderCalendar::editCalendar($item->orderid);
                            }
                        }
                        // 提交事务
                        Db::commit();
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        continue;
                    }
                }
            }
        } catch (\Exception $e) {
            $output->writeln($e->getMessage());
        }

        $output->writeln("success");
    }
}
